package com.hugedata.cdn.service.task.impl;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.hadoop.hdfs.protocol.datatransfer.Sender;
import org.apache.log4j.Logger;
import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.transaction.TransactionStatus;

import com.hugedata.cdn.base.services.BaseServiceImpl;
import com.hugedata.cdn.outerfacade.serviceadapter.soapagent.bean.TaskInfo;
import com.hugedata.cdn.outerfacade.serviceadapter.soapagent.req.IDCTaskChildNode;
import com.hugedata.cdn.outerfacade.serviceadapter.soapagent.req.TaskOnConditionReq;
import com.hugedata.cdn.outerfacade.serviceadapter.soapagent.request.AddTaskRequest;
import com.hugedata.cdn.outerfacade.serviceadapter.soapagent.request.DelTaskRequest;
import com.hugedata.cdn.outerfacade.serviceadapter.soapagent.request.ModTaskRequest;
import com.hugedata.cdn.outerfacade.serviceadapter.soapagent.request.ModTaskStatusRequest;
import com.hugedata.cdn.outerfacade.serviceadapter.soapagent.resp.TaskChildResponse;
import com.hugedata.cdn.outerfacade.serviceadapter.soapagent.response.AddTaskResponse;
import com.hugedata.cdn.outerfacade.serviceadapter.soapagent.response.DelTaskResponse;
import com.hugedata.cdn.service.task.bean.RunningTaskBean;
import com.hugedata.cdn.service.task.bean.TaskBean;
import com.hugedata.cdn.service.task.bean.TaskInfoSupplementBean;
import com.hugedata.cdn.service.task.bean.TaskOperaLogBean;
import com.hugedata.cdn.service.task.bean.TaskPushBean;
import com.hugedata.cdn.service.task.bean.TaskSessionBean;
import com.hugedata.cdn.service.task.bean.ToolAttrBean;
import com.hugedata.cdn.service.task.bean.ToolTaskBean;
import com.hugedata.cdn.service.task.bean.ToolTaskInfo;
import com.hugedata.cdn.service.task.bean.ToolTaskInfoHttp;
import com.hugedata.cdn.service.util.SerializeUtil;
import com.hugedata.cdn.util.CdnException;
import com.hugedata.cdn.util.CdnTransactionCallback;
import com.hugedata.cdn.util.CdnTransactionTemplate;
import com.hugedata.cdn.util.CommonUtil;
import com.hugedata.cdn.util.ResultCode;
import com.hugedata.cdn.util.SystemInspect;
import com.hugedata.imsp.jabberc.IMSPClient;
import com.hugedata.imsp.jabberc.service.node.IDCTaskNode;
import com.hugedata.imsp.jabberc.service.task.TaskOnConditionRequest;
import com.hugedata.imsp.jabberc.service.task.TaskOnConditionResponse;
import com.hugedata.imsp.jabberc.service.task.TaskRequest;
import com.hugedata.imsp.jabberc.service.task.TaskResponse;
import com.ibatis.sqlmap.client.SqlMapExecutor;

/**
 * 项目名称：xiaomifeng 类名称：TaskPushService 类描述： 创建人：zhaoaihua 创建时间：2013-10-27
 * 上午10:02:08 修改备注：
 * 
 * @version
 */
public class TaskPushService extends BaseServiceImpl
{
    /** 事务模版工具类 */
    private CdnTransactionTemplate cdnTransactionTemplate;

    private CommonUtil commonutil;

    private SerializeUtil serializeUtil;

    private SystemInspect systemInspect;

    private TaskService taskService;
    
    /**
     * 以年为单位的毫秒数
     */
    public static final long year_SIZE = 365 * 24 * 60 * 60 * 1000;

    @Override
    protected String getDomainName()
    {
        return "taskSql";
    }

    // 创建任务
    public TaskOnConditionResponse createTaskByArea(TaskOnConditionReq req)
    {
        AddTaskResponse addTaskResponse = new AddTaskResponse();

        try
        {
            // 入库信息由前台录入 后台不操作
            addTaskDB(req, addTaskResponse);
            TaskOnConditionResponse response = createTaskWithPD(req);
            return response;
        }
        catch (IllegalAccessException e)
        {
            throw new RuntimeException("create failed exception", e);
        }
        catch (InvocationTargetException e)
        {
            throw new RuntimeException("create failed exception", e);
        }
        catch (CdnException e)
        {
            throw new RuntimeException("create failed exception", e);
        }
        catch (Exception e)
        {
            throw new RuntimeException("create failed exception", e);
        }
    }

    /**
     * @Title: createTaskWithPD
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @author Wangxiaoming
     * @param req
     * @return
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws Exception
     * @throws CdnException
     * @throws
     */
    private TaskOnConditionResponse createTaskWithPD(TaskOnConditionReq req)
            throws IllegalAccessException, InvocationTargetException,
            Exception, CdnException
    {

        TaskInfo taskInfo = req.getTaskInfo();
        TaskOnConditionRequest request = new TaskOnConditionRequest();
        request.setInput(getTaskInput(taskInfo));
        request.setInputType(2);
        request.setOutputType(2);// 1 -- 文件输出， 2 -- 消息输出
        request.setOutput(systemInspect.getPushtaskInitBean().getDataPostUrl());
        request.setTaskInterval(taskInfo.getTaskInterval() * 60);

        request.setForceEndFlag(0);// 0：代表任务优先；1：代表时间优先。
        request.setBeginTime(taskInfo.getStartTime());
        request.setEndTime(taskInfo.getEndTime());

//        request.setToolId("16");
        request.setToolId(req.getToolId());
        request.setImmediate(0);

        request.setTimeOut(300 * 1000);
        // 设置优先级
        request.setTaskPriority(1);

        // BeanUtils.copyProperties(taskOnConditionRequest, req);

        // LmnTaskChildNode[] lmnArr = req.getLmnArr();
        // if (!ArrayUtils.isEmpty(lmnArr))
        // {
        // int lmnLen = ArrayUtils.getLength(lmnArr);
        // List<LmnTaskNode> lmnList = new ArrayList<LmnTaskNode>(lmnLen);
        // for (int i = 0; i < lmnLen; i++)
        // {
        // LmnTaskNode tempNode = new LmnTaskNode();
        // BeanUtils.copyProperties(tempNode, lmnArr[i]);
        // lmnList.add(tempNode);
        // }
        // taskOnConditionRequest.setLmnList(lmnList);
        // }

        IDCTaskChildNode[] idcArr = req.getIdcArr();
        if (!ArrayUtils.isEmpty(idcArr))
        {
            int idcLen = ArrayUtils.getLength(idcArr);
            List<IDCTaskNode> idcList = new ArrayList<IDCTaskNode>(idcLen);
            for (int i = 0; i < idcLen; i++)
            {
                IDCTaskNode tempNode = new IDCTaskNode();
                BeanUtils.copyProperties(tempNode, idcArr[i]);
                idcList.add(tempNode);
            }
            request.setIdcList(idcList);
        }

        // 调用测量平台接口创建任务
        TaskOnConditionResponse response = IMSPClient.getInstance()
                .createTaskByArea(request);
        int resultCode = response.getResultcode();
        if (0 == resultCode)
        {
            int taskId = response.getTaskId();
            // TaskInfo taskInfo = req.getTaskInfo();
            repairTaskDB(taskInfo, String.valueOf(taskId), null);
            logger.info("New Task SUCCESS taskId: " + taskInfo.getTaskID());

            // 当测量平台正常返回后入库sessionid
            TaskSessionBean bean = new TaskSessionBean();
            bean.setCreate_date(new Date());
            bean.setSessionid(response.getTransactionId());
            bean.setTaskid(String.valueOf(taskInfo.getTaskID()));

            taskService.insertTaskSessionId(bean);

        }
        else
        {
            logger.info("New Task FAILURE taskId: " + taskInfo.getTaskID());
        }
        log.info("-------create task-------desc:" + response.getDesc());
        return response;
    }

    public TaskChildResponse pauseTask(ModTaskStatusRequest request)
            throws Exception
    {
        TaskChildResponse resp = new TaskChildResponse();
        // "2"表暂停
        request.setStatus(2);
        // 更新数据库
        // modTaskStatusDB(request);

        int taskId = request.getTaskId();
        TaskBean taskBean = commonutil.getTaskBean(String.valueOf(taskId));
        TaskRequest taskRequest = new TaskRequest();
        taskRequest.setTaskId(NumberUtils.toInt(taskBean.getImspTask()));
        // 调用pd的删除接口

        TaskResponse taskResponse = IMSPClient.getInstance().deleteTaskByArea(
                taskRequest);
        int resultCode = resp.getResultcode();
        if (0 == resultCode)
        {
            logger.info("Delete Task SUCCESS taskId: " + taskId);
        }
        else
        {
            logger.info("Delete Task FAILURE taskId: " + taskId);
        }

        BeanUtils.copyProperties(resp, taskResponse);
        return resp;
    }

    public TaskOnConditionResponse resumeTask(ModTaskStatusRequest request)
            throws IllegalAccessException, InvocationTargetException, Exception
    {
        TaskOnConditionReq req = new TaskOnConditionReq();

        // "1"表启动
        request.setStatus(1);
        // modTaskStatusDB(request);

        // get idc list from db
        List<String> pointList = this.findTaskNodeMap(String.valueOf(request
                .getTaskId()));
        if (CollectionUtils.isNotEmpty(pointList))
        {
            int idcLen = CollectionUtils.size(pointList);
            // List<IDCTaskNode> idcList = new ArrayList<IDCTaskNode>(idcLen);
            IDCTaskChildNode[] idcArr = new IDCTaskChildNode[idcLen];
            for (int i = 0; i < idcLen; i++)
            {
                // areaCode(4位), ispCode(两位), mnCount三种内容追加组成
                String pointTempStr = pointList.get(i);
                String areaCode = StringUtils.substring(pointTempStr, 0, 4);
                String ispCode = StringUtils.substring(pointTempStr, 4, 6);
                String mnCount = StringUtils.substring(pointTempStr, 6);
                IDCTaskChildNode tempNode = new IDCTaskChildNode();
                tempNode.setAreaCode(areaCode);
                tempNode.setIspCode(ispCode);
                tempNode.setMnCount(NumberUtils.toInt(mnCount));
                idcArr[i] = tempNode;
            }
            req.setIdcArr(idcArr);
        }
        // IDCTaskNode t = new IDCTaskNode();
        // t.getMnCount()

        TaskInfo tempTask = new TaskInfo();
        tempTask.setTaskID(request.getTaskId());

        TaskInfo taskInfo = (TaskInfo) super.queryForObject("findTaskById",
                tempTask);
        req.setTaskInfo(taskInfo);

        return this.createTaskWithPD(req);
    }

    public String getToolTaskInput(ToolTaskInfo taskInfo)
    {

        ToolTaskBean bean = new ToolTaskBean();

        bean.setTaskID(String.valueOf(taskInfo.getTaskId()));
        bean.setTaskHost(taskInfo.getUrl());
        bean.setTaskPort(String.valueOf(taskInfo.getPort()));
        bean.setTaskType(Integer.parseInt(taskInfo.getTaskType()));

        // 0:网页测试
        if ("0".equals(taskInfo.getTaskType()))
        {

            bean.setTasks(taskInfo.getUrl());

            String[] fields =
            { "urlType", "tasks", "taskID", "taskType", "taskPort" };

            return bean.toTaskJson(fields);

        }

        // 0:HTTP
        else if ("1".equals(taskInfo.getTaskType()))
        {

            ToolAttrBean[] attrs = taskInfo.getAttrs();

            if (null != attrs && attrs.length > 0)
            {
                ToolTaskInfoHttp http = new ToolTaskInfoHttp();

                try
                {
                    for (ToolAttrBean attr : attrs)
                    {
                        if (attr.getAttrId() == 1001)
                        {
                            http.setRequestMode(Integer.parseInt(attr
                                    .getAttrValue()));
                        }
                        else if (attr.getAttrId() == 1002)
                        {
                            http.setNocache(Integer.parseInt(attr
                                    .getAttrValue()));
                        }
                        else if (attr.getAttrId() == 1003)
                        {
                            http.setCookies(attr.getAttrValue());
                        }
                        else if (attr.getAttrId() == 1004)
                        {
                            http.setReferer(attr.getAttrValue());
                        }
                        else if (attr.getAttrId() == 1005)
                        {
                            http.setPrimaryIP(attr.getAttrValue());
                        }
                        else if (attr.getAttrId() == 1006)
                        {
                            http.setUserAgent(attr.getAttrValue());
                        }
                    }
                }
                catch (Exception e)
                {
                    System.out.println(e);
                }

                bean.setAdvancedOptions(http);
                String[] fields =
                { "taskID", "taskType", "taskHost", "taskPort",
                        "advancedOptions", "requestMode", "nocache", "cookies",
                        "referer", "primaryIP", "userAgent" };

                return bean.toTaskJson(fields);
            }
            else
            {
                String[] fields =
                { "taskID", "taskType", "taskHost", "taskPort" };

                return bean.toTaskJson(fields);
            }
        }
        // 2:trace
        else if ("2".equals(taskInfo.getTaskType()))
        {

            String[] fields =
            { "taskID", "taskType", "taskHost" };

            return bean.toTaskJson(fields);

        }
        // 3:SMTP
        else if ("3".equals(taskInfo.getTaskType()))
        {

            String[] fields =
            { "taskID", "taskType", "taskHost", "taskPort" };

            return bean.toTaskJson(fields);

        }
        // 4:PING
        else if ("4".equals(taskInfo.getTaskType()))
        {

            String[] fields =
            { "taskID", "taskType", "taskHost" };

            return bean.toTaskJson(fields);

        }
        // 5:CDN
        else if ("5".equals(taskInfo.getTaskType()))
        {
        }
        // 6:IP反向解析
        else if ("6".equals(taskInfo.getTaskType()))
        {
        }
        // 7:DNS
        else if ("7".equals(taskInfo.getTaskType()))
        {

            String[] fields =
            { "taskID", "taskType", "taskHost" };

            return bean.toTaskJson(fields);

        }

        // 8:IP/URL定位
        else if ("8".equals(taskInfo.getTaskType()))
        {

            String[] fields =
            { "taskID", "taskType", "taskHost" };

            return bean.toTaskJson(fields);

        }

        return null;
    }

    /**
     * addTaskDB 发送任务后，修护任务关系表
     * 
     * @param AddTaskRequest
     * @param AddTaskResponse
     * @return boolean
     * @Exception 异常对象
     */
    public boolean modTaskStatus(ModTaskStatusRequest request)
            throws CdnException
    {
        try
        {
            modTaskStatusDB(request);

        }
        catch (CdnException e)
        {
            throw e;

        }

        // push taskinfo
        getExecuter().execute(new ModTaskStatusWorkThread(request));

        return true;

    }

    private class ModTaskStatusWorkThread implements Runnable
    {

        private ModTaskStatusRequest request;

        public ModTaskStatusWorkThread(ModTaskStatusRequest request)
        {
            this.request = request;
        }

        public void run()
        {

            try
            {

                // 使用的nodes
                int[] intTemp = null;

                TaskInfo taskInfo = findTaskinfoDetailByTaskid(String
                        .valueOf(request.getTaskId()));

                // 激活
                if (request.getStatus() == 1)
                {

                    Set<String> nodes = new HashSet<String>();

                    // 本次需要使用的节点
                    List<String> useNodeIds = new ArrayList<String>();
                    List<RunningTaskBean> runbeans = taskService
                            .findchildTasksByTaskid(String.valueOf(request
                                    .getTaskId()));

                    if (null != runbeans)
                    {

                        for (RunningTaskBean runbean : runbeans)
                        {

                            useNodeIds.add(runbean.getNodeID());
                        }

                    }
                    nodes.addAll(useNodeIds);

                    Object[] temp = (Object[]) nodes.toArray();

                    intTemp = new int[temp.length];
                    for (int i = 0; i < temp.length; i++)
                    {
                        intTemp[i] = Integer.parseInt((String) temp[i]);
                    }

                }
                else if (request.getStatus() == 2)
                {

                    intTemp = new int[0];
                }

                // TODO
                TaskBean taskbean = commonutil.getTaskBean(String
                        .valueOf(request.getTaskId()));

//                TaskRequest taskRequest = new TaskRequest();

                com.hugedata.imsp.jabberc.service.task.TaskInfo taskinfobean = new com.hugedata.imsp.jabberc.service.task.TaskInfo();
                taskinfobean
                        .setTask_id(Integer.parseInt(taskbean.getImspTask()));
                taskinfobean.setInput_type(2);
                taskinfobean.setInput(getTaskInput(taskInfo));
                taskinfobean.setOutput_type(2);
                taskinfobean.setOutput(systemInspect.getPushtaskInitBean()
                        .getDataPostUrl());
                taskinfobean.setTask_interval(taskInfo.getTaskInterval() * 60);
                taskinfobean.setForce_end_flag(0);
                taskinfobean.setBegin_time(taskInfo.getStartTime());
                taskinfobean.setEnd_time(taskInfo.getEndTime());
                taskinfobean.setTool_id(taskInfo.findToolId());
                taskinfobean.setResponse_type(0);
                taskinfobean.setRollback_flag(0);

                taskinfobean.setMn_list(intTemp);

                // taskRequest.setTask(taskinfobean);
                // taskRequest
                // .setTask_id(Integer.parseInt(taskbean.getImspTask()));
                // taskRequest.setType(2);
                // taskRequest.setTimeOut(60000);
                //
                // TaskResponse taskResponse = systemInspect.getClient()
                // .modifyTask(taskRequest);
                //
                // // if push ok
                // if (taskResponse.getResultcode() == 0)
                // {
                //
                // // 维护 推送成功后 记录任务运行状态的数据
                // repairModTaskStatusDB(String.valueOf(request.getTaskId()),
                // request.getStatus());
                // }

            }
            catch (CdnException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

    /**
     * delTask 发送任务后，修护任务关系表
     * 
     * @param DelTaskRequest
     * @param DelTaskResponse
     * @return boolean
     * @Exception 异常对象
     */
    public boolean delTask(DelTaskRequest request, DelTaskResponse response)
            throws CdnException
    {

        try
        {
            delTaskDB(request, response);

        }
        catch (CdnException e)
        {
            throw e;

        }

        // push taskinfo
        getExecuter().execute(new DelTaskWorkThread(request));

        return true;

    }

    /**
     * addTaskDB 发送任务后，修护任务关系表
     * 
     * @param AddTaskRequest
     * @param AddTaskResponse
     * @return boolean
     * @Exception 异常对象
     */
    public boolean addTaskDB(final TaskOnConditionReq req,
            final AddTaskResponse response) throws CdnException
    {
        try
        {
            this.cdnTransactionTemplate.execute(new CdnTransactionCallback()
            {
                @Override
                public void doInTransactionNoResult(TransactionStatus status)
                        throws CdnException
                {
                    TaskInfo taskInfo = req.getTaskInfo();

                    // task_info
                    // 记录任务信息到任务表
                    // insertTaskinfo(taskInfo);

                    // response.setTaskId(taskInfo.getTaskID());

                    // monitoring_point_task_map
                    // 维护任务和mn测量节点的关系
                    // LmnTaskChildNode[] lmnArrChildNodes = req.getLmnArr();
                    // int lmnLen = ArrayUtils.getLength(lmnArrChildNodes);
                    // String[] monitoringPointArr = new String[lmnLen];
                    // for (int i = 0; i < lmnLen; i++)
                    // {
                    // LmnTaskChildNode tempChildNode = lmnArrChildNodes[i];
                    // monitoringPointArr[i] = tempChildNode.getIspCode() +
                    // tempChildNode.getAreaCode() +
                    // tempChildNode.getClientCount();
                    // }
                    // addTaskNodeMap(monitoringPointArr, taskInfo.getTaskID());

                    // 维护任务和idc测量节点的关系
                    IDCTaskChildNode[] idcArr = req.getIdcArr();
                    int idcLen = ArrayUtils.getLength(idcArr);
                    String[] idcPointArr = new String[idcLen];
                    for (int i = 0; i < idcLen; i++)
                    {
                        IDCTaskChildNode tempChildNode = idcArr[i];
                        idcPointArr[i] = tempChildNode.getAreaCode()
                                + tempChildNode.getIspCode()
                                + tempChildNode.getMnCount();
                    }
                    // addTaskNodeMap(idcPointArr, taskInfo.getTaskID());

                    // 维护任务和测量节点的关系
                    // batchAddTaskNodeMap(taskInfo.getPoints(),
                    // taskInfo.getTaskID());

                    String tmpTaskID = String.valueOf(taskInfo.getTaskID());
                    
                    TaskBean taskbean = commonutil.getTaskBean(String
                            .valueOf(tmpTaskID));
                    
                    // init task to task_result_info
                    taskService.initTaskResult(taskbean);
                    
                    //查询告警设置信息
//                    TaskInfoSupplementBean taskInfoSupplement = taskService.findTaskInfoSupplement(tmpTaskID);
                    
                    // task_info_push
                    // insertTaskinfoPush(taskInfo.getTaskID(), request);
                    logger.info("Into DB SUCCESS taskId: " + taskInfo.getTaskID());
                }
            });
        }
        catch (CdnException e)
        {
            log.error("db operator error , errorcode = " + e.getErrorNum());
            log.error("", e);
            logger.info("Into DB FAILURE taskId: " + req.getTaskInfo().getTaskID());
            throw e;
        }

        return true;
    }

    private String generateDatetimeStr()
    {
        Calendar cal = Calendar.getInstance();
        return DateFormatUtils.format(cal, "yyyy-MM-dd");
    }

    public TaskOnConditionResponse modTask(TaskOnConditionReq req)
            throws IllegalAccessException, InvocationTargetException,
            CdnException, Exception
    {
        // 更新数据库
        // this.modTaskDB(req);
        int taskID = req.getTaskInfo().getTaskID();

        TaskRequest taskRequest = new TaskRequest();
        TaskBean taskBean = commonutil.getTaskBean(String.valueOf(taskID));
        taskRequest.setTaskId(NumberUtils.toInt(taskBean.getImspTask()));
        TaskResponse taskResponse = IMSPClient.getInstance().deleteTaskByArea(
                taskRequest);
        logger.info("Delete Task SUCCESS taskID: " + taskID);
        int resultcode = taskResponse.getResultcode();
        if (0 != resultcode)
        {
            throw new RuntimeException("modTask failure");
        }

        // 再次调用pd的下发接口
        ModTaskStatusRequest request = new ModTaskStatusRequest();
        request.setTaskId(taskID);
        TaskOnConditionResponse response = this.resumeTask(request);
        return response;
    }

    /**
     * modTaskDB 发送任务后，修护任务关系表
     * 
     * @param AddTaskRequest
     * @param AddTaskResponse
     * @return boolean
     * @Exception 异常对象
     */
    public boolean modTaskDB(final TaskOnConditionReq request)
            throws CdnException
    {
        try
        {
            this.cdnTransactionTemplate.execute(new CdnTransactionCallback()
            {
                @Override
                public void doInTransactionNoResult(TransactionStatus status)
                        throws CdnException
                {

                    // boolean needPush = false;

                    TaskInfo taskInfo = request.getTaskInfo();

                    TaskBean taskbean = commonutil.getTaskBean(String
                            .valueOf(taskInfo.getTaskID()));

                    if (taskbean == null || null == taskbean.getImspTask())
                    {
                        throw new CdnException(Integer
                                .valueOf(ResultCode.TaskSyncError),
                                ResultCode.TaskSyncErrorDesc);
                    }

                    // task_info

                    TaskInfo taskInfotemp = findTaskinfoDetailByTaskid(String
                            .valueOf(taskInfo.getTaskID()));
                    taskInfo.setCreatTime(taskInfotemp.getCreatTime());

                    updateTaskinfo(taskInfo);

                    // task_result
                    taskService.modTaskUpdateFlag(taskbean);

                    IDCTaskChildNode[] idcArr = request.getIdcArr();
                    int idcLen = ArrayUtils.getLength(idcArr);
                    String[] idcPointArr = new String[idcLen];
                    for (int i = 0; i < idcLen; i++)
                    {
                        IDCTaskChildNode tempChildNode = idcArr[i];
                        idcPointArr[i] = tempChildNode.getAreaCode()
                                + tempChildNode.getIspCode()
                                + tempChildNode.getMnCount();
                    }
                    modTaskNodeMap(idcPointArr, taskInfo.getTaskID());
                    // List<String> taskPoints = findTaskNodeMap(String
                    // .valueOf(taskInfo.getTaskID()));

                    // String[] points = taskInfo.getPoints();

                    // points push
                    // if (!((taskPoints.containsAll(Arrays.asList(points)) &&
                    // (taskPoints
                    // .size() == points.length))))
                    // {
                    //
                    // needPush = true;
                    // // monitoring_point_task_map
                    // batchModTaskNodeMap(points, taskInfo.getTaskID());
                    //
                    // }

                    // active/pause stauts push
                    // if (taskInfo.getStatus() != taskbean.getStatus())
                    // {
                    // needPush = true;
                    // }

                    // task_info_push
                    // if (needPush)
                    // {
                    // insertTaskinfoModPush(taskInfo.getTaskID(), request);
                    //
                    // request.modIfneedPush(true);
                    // }

                }
            });
        }
        catch (CdnException e)
        {

            log.error("db operator error , errorcode = " + e.getErrorNum());

            throw e;

        }

        return false;
    }

    /**
     * modTaskStatusDB 发送任务后，修护任务关系表
     * 
     * @param AddTaskRequest
     * @param AddTaskResponse
     * @return boolean
     * @Exception 异常对象
     */
    public boolean modTaskStatusDB(final ModTaskStatusRequest request)
            throws CdnException
    {
        try
        {
            this.cdnTransactionTemplate.execute(new CdnTransactionCallback()
            {
                @Override
                public void doInTransactionNoResult(TransactionStatus status)
                        throws CdnException
                {

                    TaskBean taskbean = commonutil.getTaskBean(String
                            .valueOf(request.getTaskId()));

                    // task_info
                    if (null != taskbean)
                    {

                        if (null == taskbean.getImspTask())
                        {
                            throw new CdnException(Integer
                                    .valueOf(ResultCode.TaskSyncError),
                                    ResultCode.TaskSyncErrorDesc);
                        }

                        modtaskstatus(String.valueOf(request.getStatus()),
                                taskbean.getTaskID());

                    }

                    // task_info_push
                    insertTaskinfoModStatusPush(request.getTaskId(), request);

                }
            });
        }
        catch (CdnException e)
        {

            log.error("db operator error , errorcode = " + e.getErrorNum());

            throw e;

        }

        return true;
    }

    /**
     * delTaskDB 发送任务后，修护任务关系表
     * 
     * @param AddTaskRequest
     * @param AddTaskResponse
     * @return boolean
     * @Exception 异常对象
     */
    public boolean delTaskDB(final DelTaskRequest request,
            final DelTaskResponse response) throws CdnException
    {
        try
        {
            this.cdnTransactionTemplate.execute(new CdnTransactionCallback()
            {
                @Override
                public void doInTransactionNoResult(TransactionStatus status)
                        throws CdnException
                {

                    TaskBean taskbean = commonutil.getTaskBean(String
                            .valueOf(request.getTaskId()));

                    // task_info
                    if (null != taskbean)
                    {

                        taskbean.setStatus(0);
                        taskbean.setCancelTime(new Timestamp(System
                                .currentTimeMillis()));
                        modtaskstatusbean(taskbean);

                    }

                    // monitoring_point_task_map
                    // pd删除任务(前端取消任务)，删除taskId和idc关系->>现在改为屏蔽此操作
                    // deleteAllByTaskId(taskbean.getTaskID());

                    // task_info_push
                    insertTaskinfoDelPush(request.getTaskId(), request);

                    logger.info("Into DB SUCCESS taskId: " + request.getTaskId());
                }
            });
        }
        catch (CdnException e)
        {

            log.error("db operator error , errorcode = " + e.getErrorNum());
            log.error("delTaskDB exception", e);
            throw e;

        }

        return true;
    }

    /**
     * repairTaskDB 发送任务后，修护任务内存动态关系表
     * 
     * @param addtask
     * @param modtask
     * @param deltask
     * @return boolean
     * @Exception 异常对象
     */
    public boolean repairTaskDB(final TaskInfo taskInfo,
            final String imspTaskID, final List<String> useNodeIds)
            throws CdnException
    {
        try
        {
            this.cdnTransactionTemplate.execute(new CdnTransactionCallback()
            {
                @Override
                public void doInTransactionNoResult(TransactionStatus status)
                        throws CdnException
                {

                    // 更新推送结果
                    // updateTaskinfoPush(imspTaskID,
                    // String.valueOf(taskInfo.getTaskID()));

                    // update taskinfo imspTaskID
                    // 在数据库表中维护(taskId和测量平台的taskId的一对一的关系，删除任务的时候需要根据taskId查询测量平台的taskId来传给测量平台的删除任务接口)
                    updateTaskinfoAfterPush(imspTaskID,
                            String.valueOf(taskInfo.getTaskID()));

                    TaskBean taskbean = commonutil.getTaskBean(String
                            .valueOf(taskInfo.getTaskID()));

                    // 新增的任务维护到back_child_task_info
                    // batchAddRunningTask(useNodeIds,
                    // String.valueOf(taskInfo.getTaskID()));

                    // memory maintain
                    // task map
                    // taskbean.setImspTask(findimspTaskByTaskid(taskInfo
                    // .getTaskID()));
                    taskbean.setImspTask(imspTaskID);

                    commonutil.addTaskBean(taskbean);
                    logger.info("Into DB SUCCESS taskId: " + taskInfo.getTaskID());
                }
            });
        }
        catch (CdnException e)
        {

            log.error("db operator error , errorcode", e);
            throw e;

        }

        return true;
    }

    /**
     * repairModTaskDB 发送任务后，修护任务内存动态关系表
     * 
     * @param addtask
     * @param modtask
     * @param deltask
     * @return boolean
     * @Exception 异常对象
     */
    public boolean repairModTaskDB(final TaskInfo taskInfo,
            final List<String> addNodeList, final List<String> delNodeIds)
            throws CdnException
    {
        try
        {
            this.cdnTransactionTemplate.execute(new CdnTransactionCallback()
            {
                @Override
                public void doInTransactionNoResult(TransactionStatus status)
                        throws CdnException
                {

                    // 更新推送结果
                    updateTaskinfoModPush(String.valueOf(taskInfo.getTaskID()));

                    TaskBean taskbean = taskService.findTaskinfoByID(String
                            .valueOf(taskInfo.getTaskID()));

                    // 新增的任务维护到back_child_task_info
                    batchAddRunningTask(addNodeList,
                            String.valueOf(taskInfo.getTaskID()));

                    // del back_child_task_info
                    batchdelRunningTask(delNodeIds,
                            String.valueOf(taskInfo.getTaskID()));

                    // task_oprea_log
                    batchAddOperaLog(addNodeList, delNodeIds,
                            String.valueOf(taskInfo.getTaskID()));

                    // memory maintain
                    // task map
                    commonutil.modTaskBean(taskbean);
                    for (String nodeId : addNodeList)
                    {

                        // node-taskNum map taskNum++
                        commonutil.updateSuitedNodeTaskNUm(nodeId);

                        // task-nodeNum map
                        commonutil.addTNmap(taskbean.getTaskID());
                    }

                }
            });
        }
        catch (CdnException e)
        {

            log.error("db operator error , errorcode = " + e.getErrorNum());

            throw e;

        }

        return true;
    }

    /**
     * repairDelTaskDB 发送任务后，修护任务内存动态关系表
     * 
     * @param addtask
     * @param modtask
     * @param deltask
     * @return boolean
     * @Exception 异常对象
     */
    public boolean repairModTaskStatusDB(final String taskId,
            final int operastatus) throws CdnException
    {
        try
        {
            this.cdnTransactionTemplate.execute(new CdnTransactionCallback()
            {
                @Override
                public void doInTransactionNoResult(TransactionStatus status)
                        throws CdnException
                {

                    // 更新推送结果
                    updateTaskinfoModStatusPush(taskId);

                    // task_oprea_log
                    insertOperaLog(operastatus, taskId);

                }
            });
        }
        catch (CdnException e)
        {

            log.error("db operator error , errorcode = " + e.getErrorNum());

            throw e;

        }

        return true;
    }

    /**
     * repairDelTaskDB 发送任务后，修护任务内存动态关系表
     * 
     * @param addtask
     * @param modtask
     * @param deltask
     * @return boolean
     * @Exception 异常对象
     */
    public boolean repairDelTaskDB(final String taskId,
            final List<String> delNodeIds) throws CdnException
    {
        try
        {
            this.cdnTransactionTemplate.execute(new CdnTransactionCallback()
            {
                @Override
                public void doInTransactionNoResult(TransactionStatus status)
                        throws CdnException
                {

                    // 更新推送结果
                    updateTaskinfoDelPush(taskId);

                    // del back_child_task_info
                    batchdelRunningTask(delNodeIds, taskId);

                    // task_oprea_log
                    insertOperaLog(0, taskId);

                    // memory maintain
                    // task map
                    commonutil.delTaskBean(taskId);
                    commonutil.delTNMap(taskId);

                }
            });
        }
        catch (CdnException e)
        {

            log.error("db operator error , errorcode = " + e.getErrorNum());

            throw e;

        }

        return true;
    }

    /**
     * insertTaskinfo 新增taskinfo
     * 
     * @param TaskInfo
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void insertTaskinfo(TaskInfo taskInfo) throws CdnException
    {

        this.insert("addtaskpush", taskInfo);
    }

    /**
     * updateTaskinfo 更新taskinfo
     * 
     * @param TaskBean
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void updateTaskinfo(TaskInfo taskInfo) throws CdnException
    {

        this.update("modtaskpush", taskInfo);

    }

    public void modtaskstatus(String status, String taskId) throws CdnException
    {

        Map<String, String> map = new HashMap<String, String>();
        map.put("status", status);
        map.put("taskId", taskId);

        this.update("modtaskstatus", map);

    }

    public void modtaskstatusbean(TaskBean bean) throws CdnException
    {

        this.update("modtaskstatusbean", bean);

    }

    /**
     * insertTaskinfoPush 新增insertTaskinfoReplenish
     * 
     * @param insertTaskinfoReplenish
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void insertTaskinfoPush(int taskId, AddTaskRequest bean)
            throws CdnException
    {

        TaskPushBean pushbean = new TaskPushBean();
        pushbean.setTaskId(taskId);
        pushbean.setTaskinfoBytes(serializeUtil.serializeObject(bean));
        pushbean.setIsCommit(0);

        this.insert("insertTaskinfoPush", pushbean);
    }

    /**
     * insertTaskinfoModPush 新增insertTaskinfoReplenish
     * 
     * @param insertTaskinfoReplenish
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void insertTaskinfoModPush(int taskId, ModTaskRequest bean)
            throws CdnException
    {

        TaskPushBean pushbean = new TaskPushBean();
        pushbean.setTaskId(taskId);
        pushbean.setTaskinfoBytes(serializeUtil.serializeObject(bean));
        pushbean.setIsCommit(0);

        this.insert("insertTaskinfoModPush", pushbean);
    }

    /**
     * insertTaskinfoModPush 新增insertTaskinfoReplenish
     * 
     * @param insertTaskinfoReplenish
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void insertTaskinfoModStatusPush(int taskId,
            ModTaskStatusRequest bean) throws CdnException
    {

        TaskPushBean pushbean = new TaskPushBean();
        pushbean.setTaskId(taskId);
        pushbean.setTaskinfoBytes(serializeUtil.serializeObject(bean));
        pushbean.setIsCommit(0);

        this.insert("insertTaskinfoModStatusPush", pushbean);
    }

    /**
     * insertTaskinfoDelPush 新增insertTaskinfoReplenish
     * 
     * @param insertTaskinfoReplenish
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void insertTaskinfoDelPush(int taskId, DelTaskRequest bean)
            throws CdnException
    {

        TaskPushBean pushbean = new TaskPushBean();
        pushbean.setTaskId(taskId);
        pushbean.setTaskinfoBytes(serializeUtil.serializeObject(bean));
        pushbean.setIsCommit(0);

        this.insert("insertTaskinfoDelPush", pushbean);
    }

    /**
     * findTaskinfoPush 获取未提交的推送消息
     * 
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    @SuppressWarnings("unchecked")
    public List<TaskPushBean> findTaskinfoNeedPush() throws CdnException
    {

        return (List<TaskPushBean>) this.queryForList("findTaskinfoPushs");

    }

    /**
     * findTaskinfoPush 获取未提交的推送消息
     * 
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    @SuppressWarnings("unchecked")
    public List<TaskPushBean> findTaskinfoModNeedPush() throws CdnException
    {

        return (List<TaskPushBean>) this.queryForList("findTaskinfoModPushs");

    }

    /**
     * findTaskinfoPush 获取未提交的推送消息
     * 
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    @SuppressWarnings("unchecked")
    public List<TaskPushBean> findTaskinfoModStatusNeedPush()
            throws CdnException
    {

        return (List<TaskPushBean>) this
                .queryForList("findTaskinfoModstatusPushs");

    }

    /**
     * findTaskinfoPush 获取未提交的推送消息
     * 
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    @SuppressWarnings("unchecked")
    public List<TaskPushBean> findTaskinfoDelNeedPush() throws CdnException
    {

        return (List<TaskPushBean>) this.queryForList("findTaskinfoDelPushs");

    }

    /**
     * modTaskUpdateFlag 更新已修改任务的标记位
     * 
     * @param TaskBean
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void updateTaskinfoPush(String imspTaskId, String taskID)
            throws CdnException
    {

        Map<String, String> map = new HashMap<String, String>();
        map.put("imspTaskId", imspTaskId);
        map.put("taskId", taskID);

        this.update("updateTaskinfoPush", map);

    }

    /**
     * modTaskUpdateFlag 更新已修改任务的标记位
     * 
     * @param TaskBean
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void updateTaskinfoAfterPush(String imspTaskId, String taskID)
            throws CdnException
    {

        Map<String, String> map = new HashMap<String, String>();
        map.put("imspTaskId", imspTaskId);
        map.put("taskId", taskID);

        this.update("updateTaskinfoAfterPush", map);

    }

    /**
     * modTaskUpdateFlag 更新已修改任务的标记位
     * 
     * @param TaskBean
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void updateTaskinfoModPush(String taskID) throws CdnException
    {

        this.update("updateTaskinfoModPush", taskID);

    }

    /**
     * modTaskUpdateFlag 更新已修改任务的标记位
     * 
     * @param TaskBean
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void updateTaskinfoModStatusPush(String taskID) throws CdnException
    {

        this.update("updateTaskinfoModStatusPush", taskID);

    }

    /**
     * modTaskUpdateFlag 更新已修改任务的标记位
     * 
     * @param TaskBean
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void updateTaskinfoDelPush(String taskID) throws CdnException
    {

        this.update("updateTaskinfoDelPush", taskID);

    }

    /**
     * findTaskinfoPushByTaskid 获取指定推送消息 for test
     * 
     * @return TaskPushBean
     * @throws CdnException
     * @Exception 异常对象
     */

    public TaskPushBean findTaskinfoPushByTaskid(int taskId)
            throws CdnException
    {

        return (TaskPushBean) this.queryForObject("findTaskinfoPushByTaskid",
                String.valueOf(taskId));
    }

    public String findimspTaskByTaskid(int taskId) throws CdnException
    {

        return (String) this.queryForObject("findimspTaskByTaskid",
                String.valueOf(taskId));
    }

    /**
     * findTaskinfoPush 获取未提交的推送消息
     * 
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    @SuppressWarnings("unchecked")
    public List<String> findTaskNodeMap(String taskId) throws CdnException
    {

        return (List<String>) this.queryForList("findTaskNodeMap", taskId);

    }

    /**
     * @throws CdnException
     * @Title: deleteAllByTaskId
     * @Description: 获取所有结果
     * @param taskId
     *            任务编号
     * @return
     * @throws
     */
    public void deleteAllByTaskId(String taskId) throws CdnException
    {

        this.delete("deleteMapCodesByTaskId", NumberUtils.toInt(taskId));
    }

    public com.hugedata.cdn.outerfacade.serviceadapter.soapagent.bean.TaskInfo findTaskinfoDetailByTaskid(
            String taskId) throws CdnException
    {

        return (com.hugedata.cdn.outerfacade.serviceadapter.soapagent.bean.TaskInfo) this
                .queryForObject("findTaskinfoDetailByTaskid", taskId);
    }

    /**
     * insertTaskinfoDelPush 新增insertTaskinfoReplenish
     * 
     * @param insertTaskinfoReplenish
     * @throws CdnException
     * @Exception 异常对象
     * @since CodingExample　Ver(编码范例查看) 1.1
     */
    public void insertOperaLog(int operatype, String taskId)
            throws CdnException
    {

        TaskOperaLogBean logbean = new TaskOperaLogBean();
        logbean.setTaskId(taskId);
        logbean.setNodeId("0");
        logbean.setOpreaType(operatype);
        logbean.setOpreaTime(new Timestamp(System.currentTimeMillis()));

        this.insert("addtaskoprealog", logbean);
    }

    // 添加任务和测量节点的关系
    public boolean addTaskNodeMap(final String[] monitoringPointArr,
            final int taskId)
    {
        getSqlMapClientTemplate().execute(new SqlMapClientCallback<Object>()
        {
            public Object doInSqlMapClient(SqlMapExecutor executor)
                    throws SQLException
            {
                executor.startBatch();
                for (String str : monitoringPointArr)
                {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("monitoringPointId", str);
                    map.put("taskID", String.valueOf(taskId));
                    executor.insert("addtasknodemappush", map);
                }
                return executor.executeBatch();
            }
        });
        return true;
    }

    public boolean modTaskNodeMap(final String[] monitoringPointArr,
            final int taskId) throws CdnException
    {
        this.delete("deleteMapCodesByTaskId", taskId);
        this.addTaskNodeMap(monitoringPointArr, taskId);
        return true;
    }

    /**
     * batchAddTaskNodeMap 新增任务探测点
     * 
     * @param List
     *            <String>
     * @param String
     * @throws CdnException
     *             异常对象
     */
    @SuppressWarnings("unchecked")
    public boolean batchAddTaskNodeMap(final String[] points, final int taskId)
    {

        getSqlMapClientTemplate().execute(new SqlMapClientCallback<Object>()
        {
            public Object doInSqlMapClient(SqlMapExecutor executor)
                    throws SQLException
            {
                executor.startBatch();

                for (String pointid : points)
                {

                    Map<String, String> map = new HashMap<String, String>();
                    map.put("monitoringPointId", pointid);
                    map.put("taskID", String.valueOf(taskId));

                    executor.insert("addtasknodemappush", map);
                }
                return executor.executeBatch();
            }
        });

        return true;
    }

    /**
     * batchModTaskNodeMap 新增任务探测点
     * 
     * @param List
     *            <String>
     * @param String
     * @throws CdnException
     *             异常对象
     */
    @SuppressWarnings("unchecked")
    public boolean batchModTaskNodeMap(final String[] points, final int taskId)
    {

        getSqlMapClientTemplate().execute(new SqlMapClientCallback<Object>()
        {
            public Object doInSqlMapClient(SqlMapExecutor executor)
                    throws SQLException
            {
                executor.startBatch();

                // before mapping
                executor.delete("deleteMapCodesByTaskId", taskId);

                for (String pointid : points)
                {

                    Map<String, String> map = new HashMap<String, String>();
                    map.put("monitoringPointId", pointid);
                    map.put("taskID", String.valueOf(taskId));

                    executor.insert("addtasknodemappush", map);
                }
                return executor.executeBatch();
            }
        });

        return true;
    }

    /**
     * batchAddRunningTask 新增RunningTask
     * 
     * @param List
     *            <String>
     * @param String
     * @throws CdnException
     *             异常对象
     */
    @SuppressWarnings("unchecked")
    public boolean batchAddRunningTask(final List<String> nodes,
            final String taskId)
    {

        getSqlMapClientTemplate().execute(new SqlMapClientCallback<Object>()
        {
            public Object doInSqlMapClient(SqlMapExecutor executor)
                    throws SQLException
            {
                executor.startBatch();
                for (String nodeid : nodes)
                {

                    Map<String, String> map = new HashMap<String, String>();
                    map.put("nodeID", nodeid);
                    map.put("taskID", taskId);

                    executor.insert("insertChildTask", map);
                }
                return executor.executeBatch();
            }
        });

        return true;
    }

    /**
     * batchAddRunningTask 新增RunningTask
     * 
     * @param List
     *            <String>
     * @param String
     * @throws CdnException
     *             异常对象
     */
    @SuppressWarnings("unchecked")
    public boolean batchdelRunningTask(final List<String> nodes,
            final String taskId)
    {

        getSqlMapClientTemplate().execute(new SqlMapClientCallback<Object>()
        {
            public Object doInSqlMapClient(SqlMapExecutor executor)
                    throws SQLException
            {
                executor.startBatch();
                for (String nodeid : nodes)
                {

                    Map<String, String> map = new HashMap<String, String>();
                    map.put("nodeID", nodeid);
                    map.put("taskID", taskId);

                    executor.delete("deleteChildTask", map);
                }
                return executor.executeBatch();
            }
        });

        return true;
    }

    /**
     * batchAddOperaLog 新增task修改记录
     * 
     * @param List
     *            <String>
     * @param String
     * @throws CdnException
     *             异常对象
     */
    @SuppressWarnings("unchecked")
    public boolean batchAddOperaLog(final List<String> addnodes,
            final List<String> delnodes, final String taskId)
    {

        getSqlMapClientTemplate().execute(new SqlMapClientCallback<Object>()
        {
            public Object doInSqlMapClient(SqlMapExecutor executor)
                    throws SQLException
            {
                executor.startBatch();

                Timestamp currtime = new Timestamp(System.currentTimeMillis());

                for (String addnodeid : delnodes)
                {

                    TaskOperaLogBean logbean = new TaskOperaLogBean();
                    logbean.setTaskId(taskId);
                    logbean.setNodeId(addnodeid);
                    logbean.setOpreaType(4);
                    logbean.setOpreaTime(currtime);

                    executor.insert("addtaskoprealog", logbean);
                }

                for (String addnodeid : addnodes)
                {

                    TaskOperaLogBean logbean = new TaskOperaLogBean();
                    logbean.setTaskId(taskId);
                    logbean.setNodeId(addnodeid);
                    logbean.setOpreaType(3);
                    logbean.setOpreaTime(currtime);

                    executor.insert("addtaskoprealog", logbean);
                }

                return executor.executeBatch();
            }
        });

        return true;
    }

    /**
     * getExecuter 获取处理线程池
     */
    public ExecutorService getExecuter()
    {
        return commonutil.taskPushTaskPool();
    }

    public String getTaskInput(TaskInfo taskInfo)
    {
        TaskBean bean = new TaskBean();
        bean.setTaskID(String.valueOf(taskInfo.getTaskID()));
        bean.setTaskType(taskInfo.getTaskType());
        // 测评
        if (taskInfo.getTaskType() == 1)
        {
            bean.setTaskUrl(taskInfo.getTaskUrl());
            bean.setCdnUrl(taskInfo.getCdnUrl());
            bean.setIp(taskInfo.getIp());

            bean.setTasks();
            bean.setUrlType(1);
            bean.setTaskPort(taskInfo.getTaskPort());
            String[] fields =
            { "taskID", "taskType", "tasks", "urlType", "ip", "taskPort" };
            return bean.toTaskJson(fields);
        }
        return null;
    }

    @SuppressWarnings("unused")
    private class DelTaskWorkThread implements Runnable
    {

        private DelTaskRequest request;

        public DelTaskWorkThread(DelTaskRequest request)
        {
            this.request = request;
        }

        public void run()
        {

            try
            {

                // TODO

                // 本次需要使用的节点
                List<String> needDelNodeIds = new ArrayList<String>();
                List<RunningTaskBean> runbeans = taskService
                        .findchildTasksByTaskid(String.valueOf(request
                                .getTaskId()));

                if (null != runbeans)
                {

                    for (RunningTaskBean runbean : runbeans)
                    {

                        needDelNodeIds.add(runbean.getNodeID());
                    }

                }

                TaskBean taskbean = commonutil.getTaskBean(String
                        .valueOf(request.getTaskId()));

                TaskRequest taskRequest = new TaskRequest();
                taskRequest.setTaskId(Integer.parseInt(taskbean.getImspTask()));

                taskRequest.setType(3);
                taskRequest.setTimeOut(60000);

                TaskResponse taskResponse = null;
                try
                {
                    log.info("begin deleteTaskByArea-------------------taskId="
                            + taskRequest.getTaskId()
                            + "\ttype=3\ttimeOut=60000");

                    taskResponse = IMSPClient.getInstance().deleteTaskByArea(
                            taskRequest);
                    log.info("Delete Task SUCCESS taskId: " + request.getTaskId());
                    // 当测量平台正常返回后入库sessionid
                    TaskSessionBean bean = new TaskSessionBean();
                    bean.setCreate_date(new Date());
                    bean.setSessionid(taskResponse.getTransactionId());
                    bean.setTaskid(String.valueOf(request.getTaskId()));

                    taskService.insertTaskSessionId(bean);
                }
                catch (Exception e)
                {
                    log.error("deleteTaskByArea exception", e);
                    throw new RuntimeException(e);
                }

                log.info("after deleteTaskByArea-------------------taskResponse.getResultcode()="
                        + taskResponse.getResultcode());
                // if push ok
                if (taskResponse.getResultcode() == 0)
                {

                    // 维护 推送成功后 记录任务运行状态的数据
                    repairDelTaskDB(String.valueOf(request.getTaskId()),
                            needDelNodeIds);
                }

            }
            catch (CdnException e)
            {
                throw new RuntimeException(e);
            }

        }
    }

    public void setCdnTransactionTemplate(
            CdnTransactionTemplate cdnTransactionTemplate)
    {
        this.cdnTransactionTemplate = cdnTransactionTemplate;
    }

    public void setCommonutil(CommonUtil commonutil)
    {
        this.commonutil = commonutil;
    }

    public void setSerializeUtil(SerializeUtil serializeUtil)
    {
        this.serializeUtil = serializeUtil;
    }

    public void setSystemInspect(SystemInspect systemInspect)
    {
        this.systemInspect = systemInspect;
    }

    public void setTaskService(TaskService taskService)
    {
        this.taskService = taskService;
    }

}
